<template>
  <div class="class-center">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-row gutter="20">
        <el-col :span="4">
          <el-select
              v-model="activityName"
              placeholder="按活动名称查询"
              clearable
              size="medium"
              class="custom-select"
          >
            <el-option
                v-for="activity in activities"
                :key="activity.id"
                :label="activity.name"
                :value="activity.name"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
              v-model="teacherName"
              placeholder="按教师名称查询"
              clearable
              size="medium"
              class="custom-select"
          >
            <el-option
                v-for="teacher in teachers"
                :key="teacher.id"
                :label="teacher.teacherName"
                :value="teacher.teacherName"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
              v-model="className"
              placeholder="按教学班名称查询"
              clearable
              size="medium"
              class="custom-select"
          >
            <el-option
                v-for="classItem in classes"
                :key="classItem.id"
                :label="classItem.name"
                :value="classItem.name"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input
              v-model="classDesc"
              placeholder="按教学班描述查询"
              clearable
              size="medium"
              class="custom-input"
          ></el-input>
        </el-col>
        <el-col :span="8" class="search-buttons">
          <el-button type="primary" size="medium" @click="selectClasses(1)">
            查询
          </el-button>
          <el-button size="medium" @click="resetQuery">重置</el-button>
          <el-button size="medium" type="success" @click="showEditClassDialog">
            新增
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据展示区域 -->
    <el-table
        :data="classes"
        border
        style="width: 100%; margin-top: 20px"
        v-if="classes.length"
        class="custom-table"
    >
      <el-table-column prop="name" label="教学班名称" width="180" />
      <el-table-column prop="classDesc" label="描述" width="450" />
      <el-table-column prop="teacherName" label="负责教师" width="120" />
      <el-table-column prop="activityName" label="关联活动" width="160" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <div class="button-group">
            <el-button size="mini" @click="showStudents(scope.row.id)">
              配置学员
            </el-button>
            <el-button size="mini" type="primary" @click="editClass(scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="deleteClass(scope.row.id)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-empty v-else description="暂无数据" style="margin: 20px 0" />

    <!-- 分页区域 -->
    <el-pagination
        v-if="total > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        background
        style="text-align: center; margin-top: 20px"
        @current-change="fetchClasses"
    ></el-pagination>

    <!-- 学员弹窗 -->
    <el-dialog
        v-model="studentsDialogVisible"
        title="编辑班级学员"
        width="60%"
        :before-close="() => { studentsDialogVisible = false }"
    >
      <el-row :gutter="20">
        <!-- 显示当前班级已选学员 -->
        <el-col :span="12">
          <div class="dialog-section-title">当前学员</div>
          <el-table
              :data="selectedClassStudents"
              style="width: 100%"
              border
              size="small"
          >
            <el-table-column label="学员姓名" prop="stuName" />
            <el-table-column label="操作" width="150" align="center">
              <template v-slot="scope">
                <el-button size="mini" type="danger" @click="removeStudent(scope.row)">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

        <!-- 显示可选的学员 -->
        <el-col :span="12">
          <div class="dialog-section-title">可选学员</div>
          <el-table
              :data="availableStudents"
              style="width: 100%"
              border
              size="small"
          >
            <el-table-column label="学员姓名" prop="stuName" />
            <el-table-column label="操作" width="150" align="center">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="addStudent(scope.row)">
                  添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="studentsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClassStudents">保存</el-button>
      </span>
    </el-dialog>

    <!-- 编辑教学班弹窗 -->
    <el-dialog
        v-model="editClassDialogVisible"
        title="编辑教学班"
        width="50%"
        :before-close="() => { editClassDialogVisible = false }"
    >
      <el-form :model="currentClass" label-width="80px">
        <el-form-item label="教学班名称">
          <el-input v-model="currentClass.name" />
        </el-form-item>
        <el-form-item label="教学班描述">
          <el-input type="textarea" v-model="currentClass.classDesc" />
        </el-form-item>
        <el-form-item label="负责教师">
          <el-select v-model="currentClass.teacherId" placeholder="请选择教师">
            <el-option
                v-for="teacher in teachers"
                :key="teacher.id"
                :label="teacher.teacherName"
                :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联活动">
          <el-select v-model="currentClass.activityId" placeholder="请选择活动">
            <el-option
                v-for="activity in activities"
                :key="activity.id"
                :label="activity.name"
                :value="activity.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClass">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ClassCenter",
  data() {
    return {
      activityName: "", // 活动名称查询
      className: "", // 教学班名称查询
      classDesc: "", // 教学班描述查询
      teacherName: "", // 教师姓名查询

      classes: [], // 教学班数据
      teachers: [], // 教师数据
      activities: [], // 活动数据

      currentPage: 1, // 当前页码
      total: 0, // 数据总条数
      pageSize: 5, // 每页显示条数
      studentsDialogVisible: false, // 控制学员弹窗的显示
      selectedClassStudents: [], // 当前选择班级的学员列表
      allStudents: [], // 所有学员数据
      studentsToAdd: [], // 用于存储将要添加的学员ID列表
      editClassDialogVisible: false, // 控制编辑教学班弹窗的显示
      currentClass: {
        // 当前编辑的教学班数据
        id: null,
        name: "",
        classDesc: "",
        teacherId: null,
        activityId: null,
        students: [], // 当前班级的学员ID列表
      },
    };
  },
  computed: {
    // 可选学员计算属性
    availableStudents() {
      return this.allStudents.filter(
          (student) =>
              !this.selectedClassStudents.some(
                  (selected) => selected.id === student.id
              )
      );
    },
  },
  methods: {
    // 删除课程
    deleteClass(id) {
      ElMessageBox.confirm("确定删除该教学班吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
            .delete(`/manager-class/delete/${id}`, {
              headers: { Authorization: localStorage.getItem("token") },
            })
            .then(() => {
              ElMessage.success("删除成功");
              this.fetchClasses();
            });
      });
    },
    showEditClassDialog() {
      this.currentClass = {
        name: "",
        classDesc: "",
        teacherId: null,
        activityId: null,
      };
      this.editClassDialogVisible = true;
    },
    // 获取教师信息
    fetchTeacherName(teacherId) {
      return this.$axios
          .get(`/manager-teacher/teacher/${teacherId}`, {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            return response.data.data.teacherName; // 返回教师姓名
          })
          .catch((error) => {
            console.error("获取教师信息失败：", error);
            return "未知教师"; // 出现错误时返回默认值
          });
    },

    // 获取活动名称
    fetchActivityName(activityId) {
      return this.$axios
          .get(`/manager-activity/activity/${activityId}`, {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            return response.data.data.name; // 返回活动名称
          })
          .catch((error) => {
            console.error("获取活动信息失败：", error);
            return "未知活动"; // 出现错误时返回默认值
          });
    },

    // 获取教学班数据（默认加载全部或按活动名称查询）
    fetchClasses(page = 1) {
      const params = {
        currentPage: page,
      };

      this.$axios
          .get("/manager-class/classes", {
            params,
            headers: { Authorization: localStorage.getItem("token") },
          })
          .then((response) => {
            const data = response.data.data;
            this.classes = data.records || [];
            this.currentPage = data.current;
            this.total = data.total;

            // 获取每个教学班的教师信息
            this.classes = this.classes.map((classItem) => {
              this.fetchTeacherName(classItem.teacherId).then((teacherName) => {
                classItem.teacherName = teacherName; // 设置教学班的教师名称
              });
              return classItem;
            });

            // 获取每个教学班的活动名称
            this.classes = this.classes.map((classItem) => {
              this.fetchActivityName(classItem.activityId).then(
                  (activityName) => {
                    classItem.activityName = activityName; // 设置教学班的活动名称
                  }
              );
              return classItem;
            });
          })
          .catch((error) => {
            console.error("加载教学班数据失败：", error);
            this.$message.error("无法加载教学班数据，请稍后重试！");
          });
    },

    // 获取教学班数据
    selectClasses(page = 1) {
      const { activityName, className, classDesc, teacherName, pageSize } =
          this;

      this.$axios
          .get("/manager-class/select", {
            params: {
              activityName: activityName || undefined, // 活动名称查询
              className: className || undefined, // 教学班名称查询
              classDesc: classDesc || undefined, // 描述查询
              teacherName: teacherName || undefined, // 教师姓名查询
              currentPage: page,
              pageSize,
            },
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            const data = response.data.data;
            this.classes = data.records || [];
            this.currentPage = data.current;
            this.total = data.total;

            this.classes = this.classes.map((classItem) => {
              this.fetchTeacherName(classItem.teacherId).then((teacherName) => {
                classItem.teacherName = teacherName; // 设置教学班的教师名称
              });
              return classItem;
            });

            this.classes = this.classes.map((classItem) => {
              this.fetchActivityName(classItem.activityId).then(
                  (activityName) => {
                    classItem.activityName = activityName; // 设置教学班的活动名称
                  }
              );
              return classItem;
            });
          })
          .catch((error) => {
            console.error("教学班数据查询失败：", error);
            this.$message.error("无法获取教学班数据，请稍后重试");
          });
    },

    // 显示学员列表弹窗
    showStudents(classId) {
      this.currentClass.id = classId; // 设置当前班级 ID
      this.$axios
          .get(`/teaching-student-in-class/${classId}`, {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            if (response.data && response.data.data) {
              // 更新 selectedClassStudents 为整个学生对象
              this.selectedClassStudents = response.data.data; // 直接存储整个学生对象
            } else {
              this.selectedClassStudents = [];
            }
            this.studentsDialogVisible = true; // 显示学员列表弹窗
          })
          .catch((error) => {
            console.error("获取学员列表失败：", error);
            this.$message.error("无法获取学员数据，请稍后重试");
          });
    },

    // 获取所有学员
    fetchAllStudents() {
      this.$axios
          .get("/manager-student/all", {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            this.allStudents = response.data.data || [];
          })
          .catch((error) => {
            console.error("获取学员数据失败：", error);
          });
    },

    // 移除选中的学员
    removeStudent(student) {
      const index = this.selectedClassStudents.indexOf(student);
      if (index !== -1) {
        this.selectedClassStudents.splice(index, 1);
      }
    },
    addStudent(student) {
      const exists = this.selectedClassStudents.find(
          (s) => s.id === student.id
      );
      if (!exists) {
        this.selectedClassStudents.push(student);
      }
    },
    // 保存教学班的学员数据
    saveClassStudents() {
      const classData = {
        id: this.currentClass.id,
        studentIds: this.selectedClassStudents.map((student) => student.id), // 提交选中的学员ID
      };

      // 调用后端接口保存学员修改
      this.$axios
          .post(`/teaching-student-in-class/update-students`, classData, {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            this.$message.success("学员信息更新成功");
            this.studentsDialogVisible = false;
            this.fetchClasses(this.currentPage); // 刷新班级数据
          })
          .catch((error) => {
            console.error("保存学员信息失败：", error);
            this.$message.error("保存学员信息失败，请稍后重试");
          });
    },

    // 编辑教学班
    editClass(classItem) {
      this.currentClass = {
        id: classItem.id,
        name: classItem.name,
        classDesc: classItem.classDesc,
        teacherId: classItem.teacherId,
        activityId: classItem.activityId,
        students: classItem.students || [], // 获取当前班级的学员ID列表
      };
      this.editClassDialogVisible = true;
    },

    // 保存编辑后的教学班数据
    saveClass() {
      const classData = {
        id: this.currentClass.id, // 确保传递课程 ID，用于更新操作
        name: this.currentClass.name,
        classDesc: this.currentClass.classDesc,
        teacherId: this.currentClass.teacherId,
        activityId: this.currentClass.activityId,
        students: this.currentClass.students,
      };
      // 调用后端接口保存修改
      this.$axios
          .post(`/manager-class/update`, classData, {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            this.$message.success("教学班信息更新成功");
            this.editClassDialogVisible = false;
            this.fetchClasses(this.currentPage); // 刷新数据
          })
          .catch((error) => {
            console.error("保存教学班信息失败：", error);
            this.$message.error("保存教学班信息失败，请稍后重试");
          });
    },

    resetQuery() {
      this.activityName = ""; // 清空活动名称
      this.className = ""; // 清空教学班名称
      this.classDesc = ""; // 清空描述
      this.teacherName = ""; // 清空教师姓名
      this.fetchClasses(1); // 重置查询后重新加载所有数据
    },
    // 清空学员弹窗数据
    resetStudents() {
      this.selectedClassStudents = [];
    },
  },

  mounted() {
    this.fetchAllStudents();
    // 页面加载时获取教师和活动数据
    this.fetchClasses();
    this.$axios
        .get(`/manager-teacher/all`, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((response) => {
          this.teachers = response.data.data;
        })
        .catch((error) => {
          console.error("获取教师数据失败：", error);
        });

    this.$axios
        .get(`/manager-activity/all`, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((response) => {
          this.activities = response.data.data;
        })
        .catch((error) => {
          console.error("获取活动数据失败：", error);
        });
  },

  watch: {
    // 监听路由参数变化
    '$route.query': {
      immediate: true,
      handler(query) {
        if (query.showCreate === 'true') {
          // 显示新建教学班弹窗
          this.showEditClassDialog();
          // 清除 URL 参数
          this.$router.replace({ path: '/admin/class' });
        }
      }
    }
  }
};
</script>

<style scoped>
.class-center {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-bar {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-select,
.custom-input {
  width: 100%;
}

.search-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.custom-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.button-group {
  display: flex;
  gap: 5px;
}

.dialog-section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}


.el-dialog__header {
  background: linear-gradient(135deg, #6c5ce7, #a29bfe);
  color: white;
}


.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-empty {
  margin: 20px 0;
  text-align: center;
}
</style>